﻿using GN.Pay.AbpClient;
using GNBaseService.PayDemo.OrderApp;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;

namespace GNBaseService.PayDemo.Web.Controllers
{
    /// <summary>
    /// 订单控制器
    /// </summary>
    public class OrderController : PayDemoControllerBase
    {
        private readonly IPayClientDomainService payService;
        private readonly IOrderAppService orderService;

        private readonly string pay_Url;

        public OrderController(IPayClientDomainService payService,
            IOrderAppService orderService,
            IPayClientConfigureDomainService clientConfigure)
        {
            this.payService = payService;
            this.orderService = orderService;
            pay_Url = clientConfigure.ServerUrl + "/Cashie/pay";

            //  pay_Url = clientConfigure.ServerUrl + "/wap/pay";
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="orderNo"></param>
        public ActionResult PayShow()
        {
            return View();
        }

        public ActionResult PayApply(string orderNo)
        {
            try
            {
                var applyInfo = orderService
                   .OrderPayApply(new OrderApp.Dto.Input.OrderPayApplyInput() { OrderNo = orderNo });
                return this.Redirect(pay_Url + "?applyId=" + applyInfo.ApplyId);

                //  return this.Redirect(pay_Url + "/" + applyInfo.ApplyId);
            }
            catch (Exception err)
            {
                if (err != null)
                {

                }
                throw err;
            }

        }

        /// <summary>
        /// 支付通道申请
        /// </summary>
        /// <param name="orderNo"></param>
        /// <param name="channelId"></param>
        /// <returns></returns>
        public ActionResult ChannelIdPayApply(string orderNo, string channelId = "")
        {
            try
            {
                var applyInfo = orderService
                   .OrderPayChannelApply(new OrderApp.Dto.Input.OrderPayChannelApplyInput()
                   {
                       ChannelId = channelId,
                       ClientIP = "1.204.114.21",
                       OrderNo = orderNo
                   });
                return this.Redirect(applyInfo.PayUrl);
            }
            catch (Exception err)
            {
                if (err != null)
                {

                }
                throw err;
            }

        }

        public ActionResult TransfersApply(string orderNo)
        {
            var msg = orderService.TransfersApply(orderNo);

            return this.View();
        }


        //将此地址配置到对应的支付服务器的app
        /// <summary>
        /// 付款通知
        /// </summary>
        public void PayNotify()
        {
            //最简单方式
            payService.NotifyService.PayNotifyHandle(Request, Response, (msg) =>
            {
                //注：此函数若无任何异常，则视为成功，不会再次通知，
                //通知即使返回成功，也有可能再次通知，因此若相同的交易号和订单号已处理，则不在处理，但不要返回异常
                this.orderService.PayNotify(msg);
            });
        }

        //将此地址配置到对应的支付服务器的app
        /// <summary>
        /// 退款通知
        /// </summary>
        public void RefundNotify()
        {
            //最简单方式
            payService.NotifyService.RefundNotifyHandle(Request, Response, (msg) =>
            {
                if (msg.Success)
                {
                    //注：此函数若无任何异常，则视为成功，不会再次通知，
                    //通知即使返回成功，也有可能再次通知，因此若相同的申请号和订单号已处理，则不在处理，但不要返回异常
                    this.orderService.RefundNotify(msg);
                }

            });
        }

        //将此地址配置到对应的支付服务器的app
        /// <summary>
        /// 退款通知
        /// </summary>
        public void TransfersNotify()
        {
            //最简单方式
            payService.NotifyService.TransfersNotifyHandle(Request, Response, (msg) =>
            {
                //注：此函数若无任何异常，则视为成功，不会再次通知，
                //通知即使返回成功，也有可能再次通知，因此若相同的申请号和订单号已处理，则不在处理，但不要返回异常
                if (msg.Success)
                {

                }
                else
                {

                }
            });
        }

        private static NameValueCollection GetQueryString(HttpRequestBase request)
        {
            if ("POST".Equals(request.HttpMethod, StringComparison.InvariantCultureIgnoreCase))
            {
                return request.Form;
            }
            return request.QueryString;
        }

        //支付成功调用的地址，拥有一个参数，orderNo
        //将此地址配置到对应的支付服务器的app
        /// <summary>
        /// 支付返回信息
        /// </summary>
        /// <returns></returns>
        public ActionResult PayReturnInfo()
        {
            var query = GetQueryString(Request);
            string orderNo = query.Get("orderNo");
            if (string.IsNullOrWhiteSpace(orderNo))
            {
                return Content("系统出错，未指定订单号");
            }
            StringBuilder builder = new StringBuilder();
            builder.Append("支付成功:");
            builder.AppendLine("     ");
            int count = 0;
            foreach (var key in query.Keys)
            {
                if (count > 0)
                {
                    builder.Append("&");
                }
                builder.AppendFormat("{0}={1}", key, query.Get(key.ToString()));
                count++;
            }
            //订单详情页
            return Content(builder.ToString());
        }
    }
}